package com.sdb.firstapp;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private ImageView imageView;
    private Button button;
    private int[] imgDog = {R.drawable.dog1,R.drawable.dog2,R.drawable.dog3,R.drawable.dog4,R.drawable.dog5};
    private int index = 0;
    private Handler handler;
    private Boolean isPause = true;
    private final int MSG_CHANGE_DOG = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.hText);
        textView.setText(R.string.text);

        imageView = findViewById(R.id.img);
        imageView.setImageResource(R.drawable.dog1);

        button = findViewById(R.id.button);
        button.setText(R.string.next);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == MSG_CHANGE_DOG){
                    index = (index + 1) % imgDog.length;
                    imageView.setImageResource(imgDog[index]);
                    return true;
                }
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(2000);
                    }
                    catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    if (!isPause) {
                        Message message = new Message();
                        message.what = MSG_CHANGE_DOG;
                        handler.sendMessage(message);
                        Log.e("MainActity", "send change message");
                    }
                }
            }
        }).start();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause = !isPause;
            }
        });
    }
}
